// 主要的JavaScript功能

// 全局变量
let currentPage = 1;
let pageSize = 20;
let totalPages = 1;

// 工具函数
function showAlert(message, type = 'success') {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    const container = document.querySelector('.container-fluid');
    container.insertBefore(alertDiv, container.firstChild);
    
    // 3秒后自动消失
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 3000);
}

function showLoading(element) {
    element.innerHTML = '<div class="loading"></div> 加载中...';
    element.disabled = true;
}

function hideLoading(element, originalText) {
    element.innerHTML = originalText;
    element.disabled = false;
}

// API请求函数
async function apiRequest(url, options = {}) {
    try {
        const response = await fetch(url, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.error('API请求失败:', error);
        showAlert('请求失败，请检查网络连接', 'danger');
        return null;
    }
}

// 数据搜索功能
function initDataSearch() {
    const searchForm = document.getElementById('searchForm');
    const dataTable = document.getElementById('dataTable');
    const pagination = document.getElementById('pagination');
    
    if (!searchForm) return;
    
    // 搜索按钮事件
    searchForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        await searchData();
    });
    
    // 导出按钮事件
    const exportBtn = document.getElementById('exportBtn');
    if (exportBtn) {
        exportBtn.addEventListener('click', exportData);
    }
    
    // 初始加载
    searchData();
}

async function searchData() {
    const searchBtn = document.getElementById('searchBtn');
    const originalText = searchBtn.innerHTML;
    
    showLoading(searchBtn);
    
    const formData = new FormData(document.getElementById('searchForm'));
    const params = new URLSearchParams();
    
    params.append('page', currentPage);
    params.append('size', pageSize);
    params.append('prodCat', formData.get('prodCat') || '');
    params.append('prodName', formData.get('prodName') || '');
    
    const response = await apiRequest(`/api/data/search?${params}`);
    
    if (response && response.code === 200) {
        displayData(response.data.records);
        updatePagination(response.data.total, response.data.pageSize);
    }
    
    hideLoading(searchBtn, originalText);
}

function displayData(data) {
    const tbody = document.querySelector('#dataTable tbody');
    if (!tbody) return;
    
    tbody.innerHTML = '';
    
    if (data.length === 0) {
        tbody.innerHTML = '<tr><td colspan="10" class="text-center">暂无数据</td></tr>';
        return;
    }
    
    data.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.prodCat || '-'}</td>
            <td>${item.prodPcat || '-'}</td>
            <td>${item.prodName || '-'}</td>
            <td>${item.lowPrice || '-'}</td>
            <td>${item.avgPrice || '-'}</td>
            <td>${item.highPrice || '-'}</td>
            <td>${item.specInfo || '-'}</td>
            <td>${item.place || '-'}</td>
            <td>${item.unitInfo || '-'}</td>
            <td>${item.pubDate || '-'}</td>
        `;
        tbody.appendChild(row);
    });
}

function updatePagination(total, size) {
    const pagination = document.getElementById('pagination');
    if (!pagination) return;
    
    totalPages = Math.ceil(total / size);
    
    let paginationHTML = '';
    
    // 上一页
    paginationHTML += `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a>
        </li>
    `;
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            paginationHTML += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                </li>
            `;
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            paginationHTML += '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }
    
    // 下一页
    paginationHTML += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a>
        </li>
    `;
    
    pagination.innerHTML = paginationHTML;
}

function changePage(page) {
    if (page < 1 || page > totalPages) return;
    currentPage = page;
    searchData();
}

async function exportData() {
    const exportBtn = document.getElementById('exportBtn');
    const originalText = exportBtn.innerHTML;
    
    showLoading(exportBtn);
    
    const formData = new FormData(document.getElementById('searchForm'));
    const params = new URLSearchParams();
    params.append('prodCat', formData.get('prodCat') || '');
    params.append('prodName', formData.get('prodName') || '');
    
    try {
        const response = await fetch(`/export_excel?${params}`);
        if (response.ok) {
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `农产品数据_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
            showAlert('导出成功！');
        } else {
            showAlert('导出失败', 'danger');
        }
    } catch (error) {
        console.error('导出失败:', error);
        showAlert('导出失败，请重试', 'danger');
    }
    
    hideLoading(exportBtn, originalText);
}

// 图表功能
function initCharts() {
    // 价格分布图表
    initPriceDistribution();
    
    // 价格统计图表
    initPriceStatistics();
    
    // 价格预测图表
    initPricePrediction();
    
    // 近日均价图表
    initRecentPrices();
}

async function initPriceDistribution() {
    const chartContainer = document.getElementById('priceDistributionChart');
    if (!chartContainer) return;
    
    const productSelect = document.getElementById('productSelect');
    const granularitySelect = document.getElementById('granularitySelect');
    
    async function updateChart() {
        const product = productSelect ? productSelect.value : '苹果';
        const granularity = granularitySelect ? granularitySelect.value : 'month';
        
        const response = await apiRequest(`/api/price_distribution?product=${product}&granularity=${granularity}`);
        
        if (response && response.code === 200) {
            const chartData = JSON.parse(response.chart);
            Plotly.newPlot(chartContainer, chartData.data, chartData.layout);
        }
    }
    
    if (productSelect) {
        productSelect.addEventListener('change', updateChart);
    }
    if (granularitySelect) {
        granularitySelect.addEventListener('change', updateChart);
    }
    
    updateChart();
}

async function initPriceStatistics() {
    const chartContainer = document.getElementById('priceStatisticsChart');
    const descDiv = document.getElementById('chartDescription');
    if (!chartContainer) return;
    const statTypeSelect = document.getElementById('statTypeSelect');
    function getStatTypeText(type) {
        if (type === 'avg') return '平均价格';
        if (type === 'max') return '最高价格';
        if (type === 'min') return '最低价格';
        return '价格统计';
    }
    async function updateChart() {
        const statType = statTypeSelect ? statTypeSelect.value : 'avg';
        const response = await apiRequest(`/api/price_statistics?type=${statType}`);
        if (response && response.code === 200) {
            const chartData = JSON.parse(response.chart);
            Plotly.newPlot(chartContainer, chartData.data, chartData.layout);
            // 动态生成卡片式说明
            if (descDiv && response.data) {
                let html = '';
                response.data.forEach(item => {
                    html += `<div class="col-md-3 mb-3">
                        <div class="card shadow-sm h-100">
                            <div class="card-body text-center">
                                <div class="fw-bold text-success mb-2" style="font-size:1.2rem;">${item.type}</div>
                                <div class="fs-4">${parseFloat(item.value).toFixed(2)} 元</div>
                                <div class="text-muted small mt-1">${getStatTypeText(statType)}</div>
                            </div>
                        </div>
                    </div>`;
                });
                descDiv.innerHTML = html;
            }
        } else if (descDiv) {
            descDiv.innerHTML = '<div class="text-muted">暂无统计数据</div>';
        }
    }
    if (statTypeSelect) {
        statTypeSelect.addEventListener('change', updateChart);
    }
    updateChart();
}

async function initPricePrediction() {
    const chartContainer = document.getElementById('pricePredictionChart');
    if (!chartContainer) return;
    
    const typeSelect = document.getElementById('predictionTypeSelect');
    const daysSelect = document.getElementById('predictionDaysSelect');
    
    async function updateChart() {
        const type = typeSelect ? typeSelect.value : '蔬菜';
        const days = daysSelect ? daysSelect.value : 7;
        
        const response = await apiRequest(`/api/price_prediction?type=${type}&days=${days}`);
        
        if (response && response.code === 200) {
            const chartData = JSON.parse(response.chart);
            Plotly.newPlot(chartContainer, chartData.data, chartData.layout);
        }
    }
    
    if (typeSelect) {
        typeSelect.addEventListener('change', updateChart);
    }
    if (daysSelect) {
        daysSelect.addEventListener('change', updateChart);
    }
    
    updateChart();
}

async function initRecentPrices() {
    const chartContainer = document.getElementById('recentPricesChart');
    if (!chartContainer) return;
    
    const typeSelect = document.getElementById('recentTypeSelect');
    const daysSelect = document.getElementById('recentDaysSelect');
    
    async function updateChart() {
        const type = typeSelect ? typeSelect.value : '蔬菜';
        const days = daysSelect ? daysSelect.value : 7;
        
        const response = await apiRequest(`/api/recent_prices?type=${type}&days=${days}`);
        
        if (response && response.code === 200) {
            const chartData = JSON.parse(response.chart);
            Plotly.newPlot(chartContainer, chartData.data, chartData.layout);
        }
    }
    
    if (typeSelect) {
        typeSelect.addEventListener('change', updateChart);
    }
    if (daysSelect) {
        daysSelect.addEventListener('change', updateChart);
    }
    
    updateChart();
}

// 外部系统功能
function initExternalSystem() {
    const checkBtn = document.getElementById('checkSystemBtn');
    const jumpBtn = document.getElementById('jumpBtn');
    const sameWindowBtn = document.getElementById('sameWindowBtn');
    const copyBtn = document.getElementById('copyUrlBtn');
    
    if (checkBtn) {
        checkBtn.addEventListener('click', checkExternalSystem);
    }
    
    if (jumpBtn) {
        jumpBtn.addEventListener('click', () => goToExternalSystem('_blank'));
    }
    
    if (sameWindowBtn) {
        sameWindowBtn.addEventListener('click', () => goToExternalSystem('_self'));
    }
    
    if (copyBtn) {
        copyBtn.addEventListener('click', copyCurrentUrl);
    }
    
    // 页面加载时检查系统状态
    checkExternalSystem();
}

async function checkExternalSystem() {
    const statusDiv = document.getElementById('systemStatus');
    const checkBtn = document.getElementById('checkSystemBtn');
    
    if (!statusDiv) return;
    
    const originalText = checkBtn ? checkBtn.innerHTML : '';
    if (checkBtn) {
        showLoading(checkBtn);
    }
    
    const response = await apiRequest('/api/check_external_system');
    
    if (response && response.code === 200) {
        if (response.accessible) {
            statusDiv.innerHTML = `
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> 外部系统可访问
                </div>
            `;
        } else {
            statusDiv.innerHTML = `
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i> 外部系统暂时不可访问
                </div>
            `;
        }
    } else {
        statusDiv.innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-times-circle"></i> 检查失败
            </div>
        `;
    }
    
    if (checkBtn) {
        hideLoading(checkBtn, originalText);
    }
}

function goToExternalSystem(target = '_blank') {
    const url = 'http://192.168.43.230:8080/';
    
    if (target === '_blank') {
        window.open(url, '_blank');
        showAlert('正在跳转到外部系统...');
    } else {
        window.location.href = url;
    }
}

function copyCurrentUrl() {
    const currentUrl = window.location.href;
    
    if (navigator.clipboard) {
        navigator.clipboard.writeText(currentUrl).then(() => {
            showAlert('当前地址已复制到剪贴板');
        }).catch(() => {
            showAlert('复制失败，请手动复制', 'warning');
        });
    } else {
        // 兼容旧浏览器
        const textArea = document.createElement('textarea');
        textArea.value = currentUrl;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        showAlert('当前地址已复制到剪贴板');
    }
}

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化数据搜索
    initDataSearch();
    
    // 初始化图表
    initCharts();
    
    // 初始化外部系统功能
    initExternalSystem();
    
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}); 